package com.lg.wechat.business.wxuser.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lg.system.wxuser.entity.UserGroup;
import com.lg.system.wxuser.service.UserGroupService;
import com.lg.wechat.business.wxuser.dao.WxUserDao;
import com.lg.wechat.business.wxuser.entity.WxUser;
import com.lg.wechat.business.wxuser.service.WxUserService;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dl
 * @since 2018-04-02
 */
@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserDao, WxUser> implements WxUserService {

	@Autowired
	WxMpService wxMpService;
	
	@Autowired
	UserGroupService userGroupService;
	
	@Autowired
	WxUserDao wxUserDao;
	
	public boolean save( WxUser wxUser) {
		wxUser.setGmtCreate(new Date());
		return super.insert(wxUser);
	}

	@Override
	public boolean update(WxUser wxUser) {
		wxUser.setGmtModified(new Date());
		return super.updateById(wxUser);
	}
	
	
	@Override
	public boolean deleteById(Long id) {
		return super.deleteById(id);
	}

	@Override
	public boolean deleteByIds(List<Long> ids) {
		if(null==ids||ids.isEmpty()){
			return false;
		}
		return super.deleteBatchIds(ids);
	}

	@Override
	public WxUser selectByOpenId(String openId) {
		EntityWrapper<WxUser>  wrapper = new EntityWrapper<WxUser>();
		wrapper.eq("open_id", openId);
		return selectOne(wrapper);
	}

	@Override
	public boolean move(List<Long> ids,  List<Long> gids) throws WxErrorException {
		List<WxUser> wxUsers=selectBatchIds(ids);
		List<String> openids=new ArrayList<>();
		for(WxUser wxUser: wxUsers){
			openids.add(wxUser.getOpenId());
		}
		String[] userIds = new String[openids.size()];
		openids.toArray(userIds);
		for(Long gid:gids ){//批量为用户打标签
			wxMpService.getUserTagService().batchTagging(gid, userIds);
		}
		//将关系保存到数据库
		Map<String, Object> param=new HashMap<>();
		List<UserGroup> userGroups=new ArrayList<>();
		for(Long uid:ids){
			for(Long gid:gids){
				//首先判断该用户是否已经打过标签打过的话就不在打了
				param.put("user_id", uid);
				param.put("group_id", gid);
				if(userGroupService.selectByMap(param).isEmpty()){
					UserGroup userGroup=new UserGroup();
					userGroup.setUserId(uid);
					userGroup.setGroupId(gid);
					userGroups.add(userGroup);
				}
			}
		}
		if(!userGroups.isEmpty()){
			return userGroupService.insertBatch(userGroups);
		}
		return true;
	}

	@Override
	public List<WxUser> selectListByXml(WxUser wxUser) {
		return wxUserDao.selectListByXml(wxUser);
	}

}
